"""
序列化器
"""
from django.forms import model_to_dict
from rest_framework import serializers
from account.models import Account, Role, Resource


class AccountManageSerializer(serializers.ModelSerializer):
    """
    用户组序列化器
    """
    id = serializers.SerializerMethodField()

    class Meta:
        """
        序列化模型
        """
        model = Account
        fields = '__all__'

    def get_id(self, obj):
        return obj.id


class RoleInfoSerializer(serializers.ModelSerializer):
    children = serializers.SerializerMethodField()
    tid = serializers.SerializerMethodField()
    class Meta:
        """
        序列化模型
        """
        model = Role
        fields = ['id', 'name', 'children', 'desc', 'tid']

    def get_tid(self, obj):
        return obj.id

    def get_children(self, obj):
        resource_query_list = obj.resource.all()
        resource_list = []
        for i in resource_query_list:
            if i.status == 1:
                data = model_to_dict(i)
                data.update({'tid': int(str(obj.id) + str(i.id))})
                resource_list.append(data)
        # resource_list = [model_to_dict(i).update({'tid': str(obj.id) + str(i.id)}) for i in resource_query_list if i.status == 1]
        return resource_list


class AccountRoleInfoSerializer(serializers.ModelSerializer):
    role_list = serializers.SerializerMethodField()

    class Meta:
        """
        序列化模型
        """
        model = Account
        fields = '__all__'

    def get_role_list(self, obj):
        # 获取该用户的角色列表
        role_list = obj.role_set.all()
        result_list = []
        for role in role_list:
            # role ---》 obj对象
            # 获取当前角色的所有权限资源
            resource_query_list = role.resource.all()
            # 将对应的权限资源数据格式化
            resource_list = []
            for i in resource_query_list:
                if i.status == 1:
                    data = model_to_dict(i)
                    data.update({'tid': int(str(role.id) + str(i.id))})
                    resource_list.append(data)
            # resource_list = [model_to_dict(i).update({'tid': str(role.id) + str(i.id)}) for i in resource_query_list if i.status == 1]
            result_list.append({
                'id': role.id,
                'name': role.name,
                'children': resource_list,
                'desc': role.desc,
                'tid': role.id
            })
        return result_list



